//
//  VoiceView.m
//  YuTang
//
//  Created by 葛悦彣 on 2024/8/19.
//

#import "VoiceView.h"
#import "SYAudio.h"
#import "SoundRecordingView.h"

@interface VoiceView ()
@property (nonatomic ,strong) UIButton * btn;
@property (nonatomic ,strong) UIButton * playBtn;
@property (nonatomic ,strong) UIButton * remaveBtn;
@property (nonatomic, strong) SoundRecordingView * SoundRecordingview;
@property (nonatomic, strong) NSString *filePath;

@property (nonatomic, assign) BOOL isEnd;  // 判断是不是结束手势
@property (nonatomic, assign) BOOL isRecognize;  // 是否开始手势
@property (nonatomic,strong) NSTimer * timer;
@property (nonatomic, assign) int timeS;

@end

@implementation VoiceView


+ (instancetype)NewView {
    VoiceView * view = [VoiceView new];
    view.backgroundColor = UIColor.whiteColor;
    view.clipsToBounds = YES;
    [view newUI];
    return view;
}
- (void)newUI{
    UILabel * lab = [DTKTool labelWithText:@"备注" andFont:kCFont(17) andTextColor:KcolorHex(@"#222222")];
    [self addSubview:lab];
    [lab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(kwt(12));
        make.centerY.offset(0);
    }];
    
    MJWeakSelf
    
    UIButton * btn = [UIButton buttonWithType:UIButtonTypeSystem];
//    self.btn = btn;
    [btn addTarget:self action:@selector(OpenSoundRecording) forControlEvents:UIControlEventTouchDown];
    [btn addTarget:self action:@selector(EndSoundRecording) forControlEvents:UIControlEventTouchUpInside];
    [btn addTarget:self action:@selector(EndSoundRecording) forControlEvents:UIControlEventTouchUpOutside];
    [btn addTarget:self action:@selector(EndSoundRecording) forControlEvents:UIControlEventTouchCancel];
//    UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panAction:)];
//    [btn addGestureRecognizer:pan];
    btn.addFont(kCFont(18));
    [btn setTitle:@"按住说话" forState:UIControlStateNormal];
    [btn setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
    [btn setImage:[UIImage imageNamed:@"clock_in_voice"] forState:UIControlStateNormal];
    [btn setImageEdgeInsets:UIEdgeInsetsMake(0, 0, 0, kwt(10))];

    btn.backgroundColor = KcolorHex(@"#29B560");
    [self addSubview:btn];
    [DTKTool YJ:kwt(5) andView:btn];

    [btn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.offset(kwt(-15));
        make.centerY.offset(0);
        make.width.offset(kwt(130));
        make.height.offset(kwt(40));
    }];
    
    UIButton * playBtn = [UIButton new];
    self.playBtn = playBtn;
    [playBtn setImage:[UIImage imageNamed:@"language_playback0"] forState:UIControlStateNormal];
    [playBtn setImageEdgeInsets:UIEdgeInsetsMake(0, kwt(30), 0, kwt(-30))];
    [playBtn setTitleEdgeInsets:UIEdgeInsetsMake(0, kwt(-20), 0, kwt(20))];
    playBtn.hidden = YES;
    playBtn.backgroundColor = KcolorHex(@"#29B560");
    [self addSubview:playBtn];
    playBtn.addTarget(self,@selector(openplay));
    [DTKTool YJ:kwt(5) andView:playBtn];
    [playBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.offset(kwt(-15));
        make.centerY.offset(0);
        make.width.offset(kwt(130));
        make.height.offset(kwt(40));
    }];
    
    
    UIButton * remaveBtn = [UIButton new];
    self.remaveBtn = remaveBtn;
    remaveBtn.hidden = YES;
    [remaveBtn setImage:[UIImage imageNamed:@"delete_photo"] forState:UIControlStateNormal];
    [self addSubview:remaveBtn];
    remaveBtn.addTarget(self,@selector(removeBtnClick));
    [DTKTool YJ:kwt(5) andView:remaveBtn];
    [remaveBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.offset(kwt(-5));
        make.top.offset(kwt(1));
        make.width.offset(kwt(23));
        make.height.offset(kwt(23));
    }];
    
}
///打开录音界面
- (void)OpenSoundRecording{
    //准备录音
    MJWeakSelf;
    [[SYAudio shareAudio] audioStop];
    if(!self.filePath){
        self.filePath = [SYAudioFile SYAudioGetFilePathWithAMRDate];
    }
    [[SYAudio shareAudio] audioRecorderStartWithFilePath:self.filePath];
    self.SoundRecordingview.timeS = 0;
    self.SoundRecordingview.hidden = NO;
//    [self.SoundRecordingview openTime];
}
///准备录音界面
- (void)EndSoundRecording{
    //这里判断要重做
    [[SYAudio shareAudio] audioRecorderStop];
//    if(self.SoundRecordingview.isClose){
//        NSLog(@"结束了,录音不需要了");
//        self.SoundRecordingview.hidden = YES;
//        return;
//    } else {
//        //这里需要判断是否要上传录音
//        if(self.SoundRecordingview.type == SoundRecordingViewTypeWz || self.SoundRecordingview.type == SoundRecordingViewTypeWzEnd){
//            NSLog(@"结束了,不用录音上传");
//            return;
//        }
//    }
    NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
    
    [dict setValue:self.filePath forKey:@"FilePath"];
    NSString *fileName = [SYAudioFile SYAudioGetFileNameWithFilePath:self.filePath type:YES];
    [dict setValue:fileName forKey:@"FileName"];
    long long fileSize = [SYAudioFile SYAudioGetFileSizeWithFilePath:self.filePath];
    [dict setValue:@(fileSize) forKey:@"FileSize"];
    NSData * luYinData = [NSData dataWithContentsOfFile:self.filePath];
    NSTimeInterval fileTime = [[SYAudio shareAudio] durationAudioRecorderWithData:luYinData];
    [dict setValue:@(fileTime) forKey:@"FileTime"];
//    [self.SoundRecordingview newTime];
    if( [[NSString stringWithFormat:@"%.0f",fileTime] intValue]< 1){
        [[DTKTool getCurrentVC].view showWarning:@"录制时间太短了"];
        self.SoundRecordingview.hidden = YES;
        return;
    }
    self.SoundRecordingview.hidden = YES;

    ///准备上传代码previewUrl
    [SCNetManger PostuploadFilesWithData:luYinData CompletionHandler:^(NSString * _Nonnull url, NSString * _Nonnull previewUrl, NSData * _Nonnull data) {
        if(self.SoundBlock){
            self.SoundBlock(url, previewUrl);
            return;
        }
        if(self.SoundAndTimeBlock){
            self.SoundAndTimeBlock(url, previewUrl,[NSString stringWithFormat:@"%.0f",fileTime]);
        }
        NSLog(@"结束");
    }];
    
}
- (SoundRecordingView *)SoundRecordingview {
    if(!_SoundRecordingview){
        MJWeakSelf
        _SoundRecordingview = [SoundRecordingView NewSoundRecordingView];
        _SoundRecordingview.ovewBlock = ^{
          ///时长到了,结束
            if(weakSelf.SoundRecordingview.hidden == NO){
                [weakSelf EndSoundRecording];
            }
        };
        _SoundRecordingview.frame = CGRectMake(0, 0, KSCREEN_WIDTH, KSCREEN_HEIGHT);
        _SoundRecordingview.hidden = YES;
        [[UIApplication sharedApplication].keyWindow addSubview:_SoundRecordingview];
    }
    return _SoundRecordingview;
}
- (void)openplay{
  MJWeakSelf
    [[SYAudio shareAudio] audioPlayWithURL:self.voiceUrl andTimeBlock:^(int time) {
        ///创建定时器
        [weakSelf opentimeWithTimes:time];
    }];
}
- (void)opentimeWithTimes:(int)times{
    if(self.timer.isValid){
        [_timer invalidate];
    }
    _timer=nil;

    self.timer = [NSTimer scheduledTimerWithTimeInterval:1/3.0 target:self selector:@selector(openAudio) userInfo:nil repeats:YES];
    self.timeS = times * 3;
}
- (void)openAudio{
    self.timeS --;
    [self.playBtn setImage:[UIImage imageNamed:[NSString stringWithFormat:@"language_playback%d",self.timeS%3]] forState:UIControlStateNormal];
    if(self.timeS < 0){
        if(self.timer.isValid){
            [_timer invalidate];
        }
        _timer=nil;
        AVAudioSession *audioSession=[AVAudioSession sharedInstance];
        [audioSession setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];
        [audioSession overrideOutputAudioPort:AVAudioSessionPortOverrideNone error:nil];
        [audioSession setActive:YES error:nil];

        [self.playBtn setImage:[UIImage imageNamed:[NSString stringWithFormat:@"language_playback0"]] forState:UIControlStateNormal];
    }
}

- (void)removeBtnClick{
    [[SYAudio shareAudio] audioStop];
    if(self.removeBlock){
        self.removeBlock();
    }
    _voiceUrl = @"";
}
- (void)setVoiceUrl:(NSString *)voiceUrl{
    _voiceUrl = voiceUrl;
    if(voiceUrl.length > 0){
        self.playBtn.hidden = NO;
        self.remaveBtn.hidden = NO;
    } else {
        self.playBtn.hidden = YES;
        self.remaveBtn.hidden = YES;
    }
}
- (void)setVoiceDuration:(NSString *)voiceDuration{
    _voiceDuration = voiceDuration;
    if(voiceDuration.length > 0){
        if(![voiceDuration containsString:@"\""]){
            voiceDuration = [NSString stringWithFormat:@"%@\"",voiceDuration];
        }
    }
    [self.playBtn setTitle:voiceDuration forState:UIControlStateNormal];
}
- (void)dealloc{
    [[SYAudio shareAudio] audioStop];
    if(self.timer.isValid){
        [_timer invalidate];
    }
    _timer=nil;
    [self.playBtn setImage:[UIImage imageNamed:[NSString stringWithFormat:@"language_playback0"]] forState:UIControlStateNormal];
    AVAudioSession *audioSession=[AVAudioSession sharedInstance];
    [audioSession setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];
    [audioSession overrideOutputAudioPort:AVAudioSessionPortOverrideNone error:nil];
    [audioSession setActive:YES error:nil];
}
@end
